import sys
from  socket import *
from time import sleep

SEVER_ADDR = ("127.0.0.1",8888)

class FTPView:
    def __init__(self):
        self.handle = Handle()
    def _menu(self):
        print("""
        =============FTP SERVER================
        1.查看文件 2.下载文件 3.上传文件 4.退出程序
        =======================================
        """)
    def _select(self):
        cmd = input("请输入选项:")
        if cmd == "1":
            self.handle.do_list()
        elif cmd == "2":
            filename = input("要下载的文件名")
            self.handle.do_get(filename)
        elif cmd == "3":
            filename = input("要上传的文件名")
            self.handle.do_up(filename)
        elif cmd == "4":
            self.handle.do_quit()
        else:
            print("请输入正确的选项！！")
    def main(self):
        while True:
            self._menu()
            self._select()

class Handle:
    def __init__(self):
        self.sock = self._connect()
        self.status = {
            "ok":"成功",
            "FALL":"文件下载失败",
            "EXISTS":"文件已存在",
            "EMPTY":"文件库为空"
        }
    def _connect(self):
        sock = socket()
        sock.connect(SEVER_ADDR)
        return sock
    def do_get(self,filename):
        msg = "GET " + filename
        self.sock.send(msg.encode())
        response = self.sock.recv(128)
        if response == b'ok':
            fw = open(filename,'wb')
            while True:
                data = self.sock.recv(1024)
                if data == b'##':
                    break
                fw.write(data)
            fw.close()
        else:
            print(self.status[response])

    def do_quit(self):
        self.sock.send(b"QUIT")
        self.sock.close()
        sys.exit("谢谢使用")

    def do_up(self,filename):
        msg = "UP " +filename
        self.sock.send(msg.encode())
        response = self.sock.recv(128).decode()
        if response == 'ok':
            fr = open(filename,"rb")
            while True:
                data = fr.read(1024)
                if not data:
                    break
                self.sock.send(data)
            fr.close()
            sleep(0.1)
            self.sock.send(b"##")
        else:
            print(self.status[response])



    def do_list(self):
        self.sock.send(b"LIST")
        response = self.sock.recv(128).decode()
        if response =='ok':
            data = self.sock.recv(1024*1024)
            print(data.decode())
        else:
            print(self.status[response])

if __name__ == '__main__':
    ftp = FTPView()
    ftp.main()